<template>
  <div class="logs-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>调度日志</span>
          <el-button @click="loadLogs" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-table :data="logs" v-loading="loading" stripe>
        <el-table-column prop="job_name" label="任务名称" width="200" />
        <el-table-column label="执行时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.execute_time) }}
          </template>
        </el-table-column>
        <el-table-column label="设备数" width="100">
          <template #default="{ row }">
            {{ row.devices_count }}
          </template>
        </el-table-column>
        <el-table-column label="成功数" width="100">
          <template #default="{ row }">
            <span style="color: #52c41a;">{{ row.success_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="失败数" width="100">
          <template #default="{ row }">
            <span style="color: #f5222d;">{{ row.failed_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="消息" min-width="300" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.message || '-' }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { statsApi } from '@/api'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const logs = ref([])

const loadLogs = async () => {
  loading.value = true
  try {
    logs.value = await statsApi.getScheduleLogs()
  } catch (error) {
    ElMessage.error('加载调度日志失败')
  } finally {
    loading.value = false
  }
}

const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}

const getStatusType = (status) => {
  const map = {
    completed: 'success',
    failed: 'danger',
    running: 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    completed: '完成',
    failed: '失败',
    running: '运行中'
  }
  return map[status] || status
}

onMounted(() => {
  loadLogs()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}
</style>

